package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/users")
@RestController
@Api(tags = "用户管理接口")
//@RequiredArgsConstructor
public class UserController {

    @Autowired
    private  IUserService userService;
//    public UserController(IUserService userService) {
//        this.userService = userService;
//    }

    /**
     * 需求：基于Restful风格实现下面的接口：
     * 编号,接口,请求方式,请求路径,请求参数,返回值
     * 1.新增用户,post,/users,用户表单实体,无
     * 2.删除用户,delete,/users/{id},用户id,无
     * 3.根据id查询用户,get,/users/{id},用户id,用户vo
     * 4.根据id批量查询,get,/users,用户id集合,用户vo集合
     * 5.根据id扣减余额,put,/users/{id}/deduction/{money},用户id;扣除金额,无
     */
    @PostMapping
    @ApiOperation("新增用户")
    public void add(@RequestBody UserFormDTO userFormDTO) {
        log.info(userFormDTO.toString());
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }
    @DeleteMapping("{id}")
    @ApiOperation("删除用户")
    public void delete(@ApiParam("用户id") @PathVariable("id") Long id) {
        log.info(id.toString());
        userService.removeById(id);
    }
    @GetMapping("{id}")
    @ApiOperation("根据id查询用户")
    public UserVO findById(@ApiParam("用户id") @PathVariable("id") Long id) {
        log.info(id.toString());
        //差一个用get,多个用list
        User user = userService.getById(id);//查询到后将po返回给vo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        return userVO;
    }
    @GetMapping
    @ApiOperation("根据ids批量查询用户")
    public List<UserVO> findAll(@ApiParam("用户id的集合") @PathVariable("ids") List<Long> ids) {
        log.info(ids.toString());
        List<User> users = userService.listByIds(ids);
//        UserVO userVO = BeanUtil.copyProperties(users, UserVO.class);
        //copyProperties 拷贝一个
        //copyToList 拷贝集合
        List<UserVO> userVOS = BeanUtil.copyToList(users, UserVO.class);
        return userVOS;
    }
    //根据id扣减余额
    @PutMapping("{id}/deduction/{money}")
    @ApiOperation("根据id扣减余额")
    public void deductMoneyById(
            @ApiParam("用户id") @PathVariable("id") Long id,
            @ApiParam("扣减的金额") @PathVariable("money") Integer money) {
        userService.deductBalance(id,money);
    }
}
